package cn.itcast.web.controller.cargo;

import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.vo.ContractProductVo;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.utils.DownloadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class OutProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    /*
        url：    /cargo/contract/print.do
        作用： 进入出货表的页面
        参数：无
        返回值：cargo/print/contract-print
     */
    @RequestMapping("/print")
    public String print(){
        return "cargo/print/contract-print";
    }


    /*
       url：/cargo/contract/printExcel.do?inputDate=2015-01
       作用： 下载出货表的excel文件
       参数: inputDate 船期的年月分
       返回值：无，因为是下载
    */
   /* @RequestMapping("/printExcel")
    @ResponseBody
    public void printExcel(String inputDate) throws IOException {
        //1. 读取模板的输入流,读取resources目录下的资源使用类路径去读取， 如果读取的webapps目录下的内容使用servletContext
        ServletContext servletContext = session.getServletContext();
        InputStream inputStream = servletContext.getResourceAsStream("/make/xlsprint/tOUTPRODUCT.xlsx");

        //2. 使用模板去创建一个工作薄
        Workbook workbook = new XSSFWorkbook(inputStream);
        //3. 得到工作单
        Sheet sheet = workbook.getSheetAt(0);
        //4. 得到标题内容
        String title = inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表";
        //5. 得到第0行，设置第0行内容
        Row row = sheet.getRow(0);
        //得到第一个单元格
        Cell cell = row.getCell(1);
        cell.setCellValue(title);

        //6. 得到第二行，提取第二行的样式,以便给后面的数据去使用
        //定义一个数组存储样式
        CellStyle[] cellStyles = new CellStyle[8];
        //得到第二行
        row = sheet.getRow(2);
        for (int i = 0; i < cellStyles.length; i++) {
            cellStyles[i] = row.getCell(i+1).getCellStyle();
        }
        //7. 得到出货数的数据
        List<ContractProductVo> contractProductList = contractProductService.findByShipTime(getLoginUser().getCompanyId(), inputDate);
        //定义一个变量保存当前行
        int index = 2;
        //8. 遍历出货表的数据，把数据写到单元格里面
        if(contractProductList!=null){
            for (int i = 0; i <5800 ; i++) {
                for (ContractProductVo contractProduct : contractProductList) {
                    //创建行
                    row = sheet.createRow(index++);

                    //客户
                    String customName = contractProduct.getCustomName();
                    if(customName!=null){
                        cell =  row.createCell(1);
                        //设置样式
                        cell.setCellStyle(cellStyles[0]);
                        //设置内容
                        cell.setCellValue(customName);
                    }

                    //订单号
                    String contractNo = contractProduct.getContractNo();
                    if(contractNo!=null){
                        cell =  row.createCell(2);
                        //设置样式
                        cell.setCellStyle(cellStyles[1]);
                        //设置内容
                        cell.setCellValue(contractNo);
                    }

                    //货号
                    String productNo = contractProduct.getProductNo();
                    if(productNo!=null){
                        cell =  row.createCell(3);
                        //设置样式
                        cell.setCellStyle(cellStyles[2]);
                        //设置内容
                        cell.setCellValue(productNo);
                    }

                    //数量
                    Integer cnumber = contractProduct.getCnumber();
                    if(cnumber!=null){
                        cell =  row.createCell(4);
                        //设置样式
                        cell.setCellStyle(cellStyles[3]);
                        //设置内容
                        cell.setCellValue(cnumber);
                    }

                    //工厂
                    String factoryName = contractProduct.getFactoryName();
                    if(factoryName!=null){
                        cell =  row.createCell(5);
                        //设置样式
                        cell.setCellStyle(cellStyles[4]);
                        //设置内容
                        cell.setCellValue(factoryName);
                    }

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    //工厂交货期
                    Date deliveryPeriod = contractProduct.getDeliveryPeriod();
                    if(deliveryPeriod!=null){
                        cell =  row.createCell(6);
                        //设置样式
                        cell.setCellStyle(cellStyles[5]);
                        //设置内容
                        cell.setCellValue(dateFormat.format(deliveryPeriod));
                    }


                    //船期
                    Date shipTime = contractProduct.getShipTime();
                    if(shipTime!=null){
                        cell =  row.createCell(7);
                        //设置样式
                        cell.setCellStyle(cellStyles[6]);
                        //设置内容
                        cell.setCellValue(dateFormat.format(shipTime));
                    }


                    //贸易协议
                    String tradeTerms = contractProduct.getTradeTerms();
                    if(tradeTerms!=null){
                        cell =  row.createCell(8);
                        //设置样式
                        cell.setCellStyle(cellStyles[7]);
                        //设置内容
                        cell.setCellValue(tradeTerms);
                    }

                }
            }
        }

        //9. 设置响应头，通知浏览器是下载
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  //这个类的本质就是一个数组
        //把工作薄的内容写到数组中
        workbook.write(byteArrayOutputStream);

        new DownloadUtil().download(byteArrayOutputStream,response,"出货表.xlsx");

    }*/


    @RequestMapping("/printExcel")
    @ResponseBody
    public void printExcel(String inputDate) throws IOException {
        //1. 创建工作薄
        Workbook workbook = new SXSSFWorkbook();
        //2. 创建工作单
        Sheet sheet = workbook.createSheet("出货表");

        //3. 合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));

        //4. 得到excel大标题内容  inputDate=2015-08  2015-12
        String title = inputDate.replaceAll("-0","年").replaceAll("-","年")+"月份出货表";

        //5. 设置第0行的内容
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(1);
        //设置样式
        CellStyle cellStyle = bigTitle(workbook);
        cell.setCellStyle(cellStyle);
        //设置内容
        cell.setCellValue(title);

        //6. 准备列头的内容,创建行，设置列宽，设置单元格内容
        String[] titles = {"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
         row = sheet.createRow(1);
         //设置列宽
        sheet.setColumnWidth(0,6*256);
        sheet.setColumnWidth(1,21*256);
        sheet.setColumnWidth(2,16*256);
        sheet.setColumnWidth(3,29*256);
        sheet.setColumnWidth(4,11*256);
        sheet.setColumnWidth(5,11*256);
        sheet.setColumnWidth(6,11*256);
        sheet.setColumnWidth(7,11*256);
        sheet.setColumnWidth(8,11*256);
        sheet.setColumnWidth(9,11*256);

        //遍历所有的列头
        for (int i = 0; i < titles.length; i++) {
            String headName = titles[i];
            //创建单元格
            cell= row.createCell(i+1);
            //设置单元格的样式
            cell.setCellStyle(title(workbook));
            //设置内容
            cell.setCellValue(headName);
        }


        //7. 得到出货数的数据
        List<ContractProductVo> contractProductList = contractProductService.findByShipTime(getLoginUser().getCompanyId(), inputDate);
        //定义一个变量保存当前行
        int index = 2;
        //8. 遍历出货表的数据，把数据写到单元格里面
        if(contractProductList!=null){
            for (int i = 0; i <5800 ; i++) {
                for (ContractProductVo contractProduct : contractProductList) {
                    //创建行
                    row = sheet.createRow(index++);

                    //客户
                    String customName = contractProduct.getCustomName();
                    if(customName!=null){
                       cell =  row.createCell(1);
                        //设置内容
                        cell.setCellValue(customName);
                    }

                    //订单号
                    String contractNo = contractProduct.getContractNo();
                    if(contractNo!=null){
                        cell =  row.createCell(2);

                        //设置内容
                        cell.setCellValue(contractNo);
                    }

                    //货号
                    String productNo = contractProduct.getProductNo();
                    if(productNo!=null){
                        cell =  row.createCell(3);

                        //设置内容
                        cell.setCellValue(productNo);
                    }

                    //数量
                    Integer cnumber = contractProduct.getCnumber();
                    if(cnumber!=null){
                        cell =  row.createCell(4);

                        //设置内容
                        cell.setCellValue(cnumber);
                    }

                    //工厂
                    String factoryName = contractProduct.getFactoryName();
                    if(factoryName!=null){
                        cell =  row.createCell(5);

                        //设置内容
                        cell.setCellValue(factoryName);
                    }

                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    //工厂交货期
                    Date deliveryPeriod = contractProduct.getDeliveryPeriod();
                    if(deliveryPeriod!=null){
                        cell =  row.createCell(6);

                        //设置内容
                        cell.setCellValue(dateFormat.format(deliveryPeriod));
                    }


                    //船期
                    Date shipTime = contractProduct.getShipTime();
                    if(shipTime!=null){
                        cell =  row.createCell(7);

                        //设置内容
                        cell.setCellValue(dateFormat.format(shipTime));
                    }


                    //贸易协议
                    String tradeTerms = contractProduct.getTradeTerms();
                    if(tradeTerms!=null){
                        cell =  row.createCell(8);

                        //设置内容
                        cell.setCellValue(tradeTerms);
                    }

                }
            }
        }

        //9. 设置响应头，通知浏览器是下载
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  //这个类的本质就是一个数组
        //把工作薄的内容写到数组中
        workbook.write(byteArrayOutputStream);

        new DownloadUtil().download(byteArrayOutputStream,response,"出货表.xlsx");
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }
}
